<?php
/**
 * 阿里云短信操作
 * @author hw
 * @date 2022/4/13
 * @time 19:37
 */

namespace App\Services\Sms\Aliyun;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;

class AliyunSms
{
    private static $signName = "时宜网络";
    private static $accessKeyId = "LTAI5tDmpttTewNNdAMPcGPC";
    private static $accessKeySecret = "qkRFZ9Nx84CxI8FEeisusroxTOp1zy";


    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Dysmsapi Client
     */
    public static function createClient($accessKeyId = '', $accessKeySecret = '')
    {
        $config = new Config([
            // 您的 AccessKey ID
            "accessKeyId" => $accessKeyId ?: self::$accessKeyId,
            // 您的 AccessKey Secret
            "accessKeySecret" => $accessKeySecret ?: self::$accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }


    /**
     * 发送短信验证码
     * @param $phone
     * @param $code
     * @param string $signName
     * @return array
     */
    public static function sendCode($phone, $code, $signName = '')
    {
        $client = self::createClient();
        if (empty($signName)){
            $signName = self::$signName;
        }

        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $phone,
            "signName" => $signName,
            "templateCode" => "SMS_463186328",
            "templateParam" => "{\"code\":\"$code\"}"
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $response = $client->sendSmsWithOptions($sendSmsRequest, $runtime);
            return $response->body->toMap();
        } catch (\Exception $error) {
            return ['message' => $error->getMessage()];
        }
    }
}